package com.itheima.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.mapper.MenuMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.PermissionMapper;
import com.itheima.mapper.RoleMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.pojo.UserEditVo;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.*;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Autowired
    MenuMapper menuMapper;

    @Override
    public User loadUserByUsername(String username) {
        //根据用户名查询用户信息(id,密码)
        User user = userMapper.findByUserName(username);
        if (null != user) {
            //根据id查询用户的 权限集合
            //1.根据用户的id查询用户所有的角色
            Set<Role> roles = roleMapper.findByUserId(user.getId());
            if (CollectionUtil.isNotEmpty(roles)) {
                //2.循环角色集合查询角色对应的权限集合
                for (Role role : roles) {
                    Set<Permission> permissions = permissionMapper.findByRoleId(role.getId());
                    role.setPermissions(permissions);
                }
            }
            user.setRoles(roles);
        }
        return user;
    }

    @Override
    public List<Menu> getMeunList(String username) {
        List<Menu> menuList = new ArrayList<>();
        User user = userMapper.findByUserName(username);
        if (null != user) {
            //根据id查询用户的菜单集合
            //1.根据用户的id查询用户所有的角色
            Set<Role> roles = roleMapper.findByUserId(user.getId());
            if (CollectionUtil.isNotEmpty(roles)){
                //循环roles获得roles的id,获取到所有的一级菜单
                for (Role role : roles) {
                     menuList = menuMapper.findMenuByid(role.getId());
                    //每个一级菜单中存在二级菜单，根据每个Menu中的一级菜单id获得所有的二级菜单
                    if (CollectionUtil.isNotEmpty(menuList)){
                        for (Menu menu : menuList) {
                            List<Menu> children = menuMapper.findChildrenByid(menu.getId());
                            menu.setChildren(children);
                        }
                    }
                }
            }
        }
        return menuList;
    }

    @Override
    public List<Role> findAll() {
        List<Role> roles=roleMapper.findAll();
        return roles;
    }

    @Override
    public void add(User user) {
        //添加用户的基本信息
        //获取用户的密码
        String password = user.getPassword();
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        String encodepwd = encoder.encode(password);
        user.setPassword(encodepwd);
        userMapper.addUser(user);
        //回显用户的id
        Integer userId = user.getId();
        List<Integer> roleIds = user.getRoleIds();
        setUserAndRoleBatch(roleIds, userId);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Page page = PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        String queryString=null;
        if (queryPageBean.getQueryString()!=null&&!queryPageBean.getQueryString().equals("")){
            queryString="%"+queryPageBean.getQueryString()+"%";
        }
        List<User> users=userMapper.findPage(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public UserEditVo find4Edit(Integer id) {
             User user=userMapper.findById(id);
        List<Role> roles = roleMapper.findAll();
        List<Integer> rolesIds = userMapper.findroleIdsByUserId(id);
        UserEditVo vo = new UserEditVo();
        vo.setUser(user);
        vo.setRoles(roles);
        vo.setRoleIds(rolesIds);
        return vo;
    }

    @Override
    public void edit(User user) {
     userMapper.update(user);
     userMapper.deleteByUserId(user.getId());
     setUserAndRoleBatch(user.getRoleIds(), user.getId());
    }

    @Override
    public void delete(Integer id) {
        userMapper.deleteById(id);
    }

    public void setUserAndRoleBatch(List<Integer> roleIds, Integer userId) {
        if (CollectionUtil.isNotEmpty(roleIds)) {
            List<Map> params = new ArrayList<>();
            for (Integer roleId : roleIds) {
                Map map = new HashMap<>();
                map.put("userId", userId);
                map.put("roleId", roleId);
                params.add(map);
            }
            userMapper.setCheckGroupAndCheckItemBatch(params);
        }
    }
}
